package com.ghc.androidexample.share;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.ghc.androidexample.R;
import com.ghc.androidexample.R.id;
import com.ghc.androidexample.R.layout;
import com.ghc.androidexample.R.menu;
import com.ghc.androidexample.R.string;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.nfc.NfcAdapter;
import android.nfc.NfcEvent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

public class ExFileSelectorActivity extends Activity {
	private static final String FILE_FOUND = "Found %d file(s)";
	private static final String FILE_SELECT = "Select: %s";

	private ListView mLvFile;
	private ProgressDialog mProgressDialog;
	private List<String> mFileNames;
	private Uri[] mFileUris = new Uri[10];

	private NfcAdapter mNfcAdapter;
	private FileUriCallback mFileUriCallback;
	// Flag to indicate that Android Beam is available
	private boolean mAndroidBeamAvailable = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_file_selector);
		setResult(Activity.RESULT_CANCELED, null);

		// NFC isn't available on the device
		if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_NFC)
				|| Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
			mAndroidBeamAvailable = false;
		} else {
			mAndroidBeamAvailable = true;
		}

		if (!mAndroidBeamAvailable) {
			AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
			alertDialog.setMessage(R.string.nfc_unavaible);
			alertDialog.show();
			return;
		}

		mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
		/*
		 * Instantiate a new FileUriCallback to handle requests for URIs
		 */
		mFileUriCallback = new FileUriCallback();
		// Set the dynamic callback for URI requests.
		mNfcAdapter.setBeamPushUrisCallback(mFileUriCallback, this);

		mLvFile = (ListView) findViewById(R.id.lvFileSelector);
		mLvFile.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long rowId) {
				File file = new File(mFileNames.get(position));
				file.setReadable(true, false);
		        // Get a URI for the File and add it to the list of URIs
		        Uri fileUri = Uri.fromFile(file);
		        if (fileUri != null) {
		            mFileUris[0] = fileUri;
		        } else {
		            Log.e(ExFileSelectorActivity.class.getName(), "No File URI available for file.");
		            AlertDialog.Builder alertDialog = new AlertDialog.Builder(ExFileSelectorActivity.this);
					alertDialog.setMessage(R.string.no_uri);
					alertDialog.show();
		        }
				
				TextView tvSelect = (TextView) findViewById(R.id.tvFileSelect);
				tvSelect.setText(String.format(FILE_SELECT, file.getName()));
			}
		});

		processFile();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.file_selector, menu);
		return true;
	}

	/**
	 * Callback that Android Beam file transfer calls to get files to share
	 */
	private class FileUriCallback implements NfcAdapter.CreateBeamUrisCallback {
		public FileUriCallback() {
		}

		/**
		 * Create content URIs as needed to share with another device
		 */
		@Override
		public Uri[] createBeamUris(NfcEvent event) {
			return mFileUris;
		}
	}

	private void processFile() {
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.show();
		new ProcessFileTask().execute();
	}

	private class ProcessFileTask extends
			AsyncTask<String, List<String>, List<String>> {

		@Override
		protected List<String> doInBackground(String... params) {
			List<String> fileNames = new ArrayList<String>();
			File file = new File(
					getExternalFilesDir(Environment.DIRECTORY_PICTURES),
					"images");
			File[] files = file.listFiles();
			if (files != null) {
				for (File f : files) {
					fileNames.add(f.getPath());
				}
			}
			return fileNames;
		}

		@Override
		protected void onPostExecute(List<String> result) {
			mFileNames = result;
			TextView tvCount = (TextView) findViewById(R.id.tvFileCount);
			tvCount.setText(String.format(FILE_FOUND, mFileNames.size()));

			// Add to listView
			FileSelectorAdapter adapter = new FileSelectorAdapter(
					ExFileSelectorActivity.this,
					R.layout.activity_file_selector_item,
					mFileNames.toArray(new String[] {}));
			mLvFile.setAdapter(adapter);
			adapter.notifyDataSetChanged();

			mProgressDialog.dismiss();
		}
	}

	public void onDoneClick(View v) {
		finish();
	}
}
